package com.wchen.nio.capter3_2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @作者： wchen
 * @描述：
 * @创建时间： 2018/8/1 21:43
 * @版本：Copyright 2018, Inc. All Rights Reserved.
 * @修改信息：
 */
public class TimeClientHandle2 extends SimpleChannelInboundHandler<ByteBuf> {
    private static final Logger logger = LoggerFactory.getLogger(TimeClientHandle2.class);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        byte[] data = new byte[byteBuf.readableBytes()];//byteBuf.readableBytes():获取可用的长度
        byteBuf.readBytes(data);//数据读取到数组中
        String string = new String(data,"utf-8");
        System.out.println("客户端接受到服务端返回的数据:"+string);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("... client exceptionCaught");
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("... client channelActive");
        ctx.writeAndFlush(Unpooled.copiedBuffer("我是客户端".getBytes()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("... client channelInactive");
    }
}
